package com.base.controller;

import com.base.comm.CommContent;
import com.base.po.voip.*;
import com.base.service.*;
import com.base.utils.DatabaseUtil;
import com.base.utils.IP;
import com.base.utils.Produce;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class update_TourGoods {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private TourCategoryService tourCategoryService;
	@Autowired
	private TourGoodsService tourGoodsService;
	@Autowired
	private UsersService usersService;

	// 账户信息
	@RequestMapping("/update_TourGoods")
	public ModelAndView index(HttpServletRequest request, @RequestParam(value = "id", required = true) String id)
			throws Exception {
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		TourGoods tourGoods = tourGoodsService.selectByPrimaryKey(id);
		if (tourGoods == null || tourGoods.getId() == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}

		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		Users users = usersService.selectByPrimaryKey(adminUserId);
		// 获取自建商城分类信息
		List<TourCategory> tourCategory = null;
		if(users.getRole() == 0 || users.getRole() == 1) {
			tourCategory = tourCategoryService.selectByLevel1(adminUserId,adminUserId);
			request.setAttribute("userId", adminUserId);
		}

		request.setAttribute("tourCategory", tourCategory);
		request.setAttribute("tourGoods", tourGoods);
		request.setAttribute("userId", adminUserId);


		if (adminUserId == null) {
			modelAndView.setViewName("jsp/login");
		} else {
			modelAndView.setViewName("jsp/update_TourGoods");
		}
		return modelAndView;
	}

	String SUCCESS = "success";

	// 更改商户信息
    /**
     *  修改商品信息
     * @param request
     * @param response
     * @param obj
     * @throws Exception
     */
	@RequestMapping(value = "/updateTourGoodsByJson", method = RequestMethod.POST)
	public  void  updateTourGoodsByJson(HttpServletRequest request, HttpServletResponse response,@RequestBody JSONObject obj) throws Exception {
        try {
            String id = obj.get("id").toString();
            String goodstext = obj.get("goodstext").toString();
            String showpic = obj.get("showpic").toString();
            String detailpic1 = obj.get("detailpic1").toString();
            String detailpic2 = obj.get("detailpic2").toString();
            String detailpic3 = obj.get("detailpic3").toString();
            String detailpic4 = obj.get("detailpic4").toString();
            String firstclassify = obj.get("firstclassify").toString();
            BigDecimal price=new BigDecimal(Double.parseDouble(obj.get("price").toString()));
            String introduce = obj.get("introduce").toString();
            String context = obj.get("context").toString();
            context=URLDecoder.decode(context,"UTF-8");
            // 返回参数
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=UTF-8");

            TourGoods tourGoods = tourGoodsService.selectByPrimaryKey(id);
            PrintWriter out = response.getWriter();

            if (showpic != null && showpic != "undefined" && !showpic.equals("")) {
                tourGoods.setShowpic(showpic);
            }
            if (detailpic1 != null && detailpic1 != "undefined" && !detailpic1.equals("")) {
                tourGoods.setDetailpic1(detailpic1);
            }
            if (detailpic2 != null && detailpic2 != "undefined" && !detailpic2.equals("")) {
                tourGoods.setDetailpic2(detailpic2);
            }
            if (detailpic3 != null && detailpic3 != "undefined" && !detailpic3.equals("")) {
                tourGoods.setDetailpic3(detailpic3);
            }
            if (detailpic4 != null && detailpic4 != "undefined" && !detailpic4.equals("")) {
                tourGoods.setDetailpic4(detailpic4);
            }

            int code = 0;

            if (firstclassify != null && !firstclassify.equals("undefined") && !firstclassify.equals("0")) {
                TourCategory firstCategory = tourCategoryService.selectByPrimaryKey(firstclassify);
                if (firstCategory != null) {
                    firstclassify = firstCategory.getId();
                } else {
                    out.print("未找到对应一级分类");
                    return;
                }
            } else {
                firstclassify = null;
            }

            tourGoods.setGoodstext(goodstext);
            tourGoods.setFirstclassify(firstclassify);
            tourGoods.setPrice(price);
            tourGoods.setIntroduce(introduce);
            tourGoods.setContext(context);
            if (id == null) {
                out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
                return;
            } else {
                code = tourGoodsService.updateByPrimaryKeySelective(tourGoods);
                String usernamesys = (String) request.getSession().getAttribute("useracc");
                if (code == 1) {
                    logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "旅游项目成功", usernamesys, true,
                            IP.getIpAddr(request));
                    out.print(SUCCESS);
                } else {
                    logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "旅游项目失败", usernamesys, true,
                            IP.getIpAddr(request));
                    out.print("更改失败，请您重试");
                }
            }
        }catch (JSONException e){
            PrintWriter out = response.getWriter();
            out.print("数据传入有误，检查数据");
        }
    }

	// 更改商户信息
	@RequestMapping(value = "/updateTourGoods", method = RequestMethod.POST)
	public void updateTourGoods(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id, String goodstext, String showpic, String detailpic1, String detailpic2,
			String detailpic3, String detailpic4, String detailvideo, String firstclassify, String secondclassify,
			BigDecimal price, BigDecimal derate, String introduce, String context, String standard, Byte status,
			Byte datastatus, String opentime, String account,Integer choose, String exchange, Integer stock,
			String detailslink, String supplier, String color, String size, Byte isgoods) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
//		String adminUserId = (String) request.getSession().getAttribute("adminUserId");

		TourGoods tourGoods = tourGoodsService.selectByPrimaryKey(id);
		PrintWriter out = response.getWriter();

		if(context != null && context != "undefined" && !context.equals("")) {
			if(context.length() > DatabaseUtil.getFieldCapacity()) {
				out.print("商品详情添加的图片过大");
				return;
			}
		}

		if(showpic != null && showpic != "undefined" && !showpic.equals("")) {
			tourGoods.setShowpic(showpic);
		}
		if(detailpic1 != null && detailpic1 != "undefined" && !detailpic1.equals("")) {
			tourGoods.setDetailpic1(detailpic1);
		}
		if(detailpic2 != null && detailpic2 != "undefined" && !detailpic2.equals("")) {
			tourGoods.setDetailpic2(detailpic2);
		}
		if(detailpic3 != null && detailpic3 != "undefined" && !detailpic3.equals("")) {
			tourGoods.setDetailpic3(detailpic3);
		}
		if(detailpic4 != null && detailpic4 != "undefined" && !detailpic4.equals("")) {
			tourGoods.setDetailpic4(detailpic4);
		}
		if(detailvideo != null && detailvideo != "undefined" && !detailvideo.equals("")) {
			tourGoods.setDetailvideo(detailvideo);
		}


		int code = 0;
		if(choose != null) {
			if(choose == 1) {
				tourGoods.setDetailpic1("");
				System.out.println(tourGoods.getDetailpic1());
			}
			if(choose == 2) {
				tourGoods.setDetailpic2("");
			}
			if(choose == 3) {
				tourGoods.setDetailpic3("");
			}
			if(choose == 4) {
				tourGoods.setDetailpic4("");
			}
			code = tourGoodsService.updateByPrimaryKeySelective(tourGoods);
		}

		if(firstclassify != null && !firstclassify.equals("undefined") && !firstclassify.equals("0")) {
			TourCategory firstCategory = tourCategoryService.selectByPrimaryKey(firstclassify);
			if(firstCategory != null) {
				firstclassify = firstCategory.getId();
			}else {
				out.print("未找到对应一级分类");
				return;
			}
		}else {
			firstclassify = null;
		}

		tourGoods.setGoodstext(goodstext);
		tourGoods.setFirstclassify(firstclassify);
		tourGoods.setSecondclassify(secondclassify);
		tourGoods.setPrice(price);
		tourGoods.setDerate(derate);
		tourGoods.setAccount(account);
		tourGoods.setIntroduce(introduce);
		tourGoods.setContext(context);
		tourGoods.setStandard(standard);
		tourGoods.setStatus(status);
		tourGoods.setExchange(exchange);
		tourGoods.setDetailslink(detailslink);
		tourGoods.setStock(stock);
		tourGoods.setDatastatus(datastatus);
		tourGoods.setSupplier(supplier);
		tourGoods.setColor(color);
		tourGoods.setSize(size);
		tourGoods.setIsgoods(isgoods);
		if(opentime != null && opentime.equals("1")) {
			tourGoods.setShelftime(Produce.getNowDate());
		}
		if (id == null) {
			out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
			return;
		} else {
			code = tourGoodsService.updateByPrimaryKeySelective(tourGoods);
			String usernamesys = (String) request.getSession().getAttribute("useracc");
			if (code == 1) {
				logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "旅游项目成功", usernamesys, true,
						IP.getIpAddr(request));
				out.print(SUCCESS);
			} else {
				logsService.insert(CommContent.TYPE_UPDATE, "修改" + goodstext + "旅游项目失败", usernamesys, true,
						IP.getIpAddr(request));
				out.print("更改失败，请您重试");
			}
		}
	}
}
